package com.findviewbydream.evil.helloyouth.View;

import android.content.Context;

/********************************************
 * 工程名：HelloYouth
 * 包名：com.findviewbydream.evil.helloyouth.View
 * 时间：16-6-28 下午5:39
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：动态添加布局中，测量将float值转化为dp值
 ********************************************/
public class SizeHelper
{
    public static float designedDensity = 1.5f;
    public static int designedScreenWidth = 540;
    private static Context context = null;

    private static float density;

    protected static SizeHelper helper;

    private SizeHelper()
    {
    }

    public static SizeHelper setContext(Context context)
    {
        SizeHelper sizeHelper=new SizeHelper();
        SizeHelper.context=context;
        return sizeHelper;
    }

    public static void prepare(Context c)
    {
        if (context == null || context != c.getApplicationContext())
        {
            context = c;
        }
    }

    /**
     * 根据density转换设计的px到目标机器，返回px大小
     *
     * @return 像素大小
     */
    public static int fromPx(int px)
    {
        return designToDevice(context, designedDensity, px);
    }

    /**
     * 根据屏幕宽度转换设计的px到目标机器，返回px大小
     *
     * @return 像素大小
     */
    public static int fromPxWidth(int px)
    {
        return designToDevice(context, designedScreenWidth, px);
    }

    /**
     * 根据density转换设计的dp到目标机器，返回px大小
     *
     * @return 像素大小
     */
    public static int fromDp(int dp)
    {
        int px = dipToPx(context, dp);
        return designToDevice(context, designedDensity, px);
    }

    public static int dipToPx(Context context, int dip)
    {
        if (density <= 0.0F)
        {
            density = context.getResources().getDisplayMetrics().density;
        }

        return (int) ((float) dip * density + 0.5F);
    }

    public static int designToDevice(Context context, float designScreenDensity, int designPx)
    {
        if (density <= 0.0F)
        {
            density = context.getResources().getDisplayMetrics().density;
        }

        return (int) ((float) designPx * density / designScreenDensity + 0.5F);
    }

}
